import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class ScrollListenerDemoPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return ScrollListenerDemoPageState();
  }
}

class ScrollListenerDemoPageState extends State<ScrollListenerDemoPage> {
  ScrollController _scrollController = ScrollController();

  // 是否到达底部
  bool isEnd = false;

  // 位置
  double position = 0;

  // 对下拉列表监听
  String notify = "";

  // 下拉列表的数量
  int _count = 100;

  initState() {
    super.initState();
    _scrollController.addListener(() {
      setState(() {
        position = _scrollController.offset;
        isEnd = _scrollController.position.maxScrollExtent ==
            _scrollController.position.pixels;
        print(position);
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('滑动监听例子')),
      body: NotificationListener(
        onNotification: (notification) {
          String notify = "";
          if (notification is ScrollEndNotification) {
            notify = "ScrollEnd";
          } else if (notification is ScrollStartNotification) {
            notify = "ScrollStart";
          } else if (notification is UserScrollNotification) {
            notify = "UserScroll";
          } else if (notification is ScrollUpdateNotification) {
            notify = "ScrollUpdate";
          }
          setState(() {
            this.notify = notify;
          });
          return false;
        },
        child: ListView.builder(
          controller: _scrollController,
          itemBuilder: (context, index) {
            return InkWell(
              child: Card(
                child: Container(
                  alignment: Alignment.centerLeft,
                  height: 40,
                  margin: EdgeInsets.symmetric(horizontal: 20),
                  child: Text('item' + index.toString()),
                ),
              ),
              onTap: () {},
            );
          },
          itemCount: _count,
        ),
      ),
      persistentFooterButtons: <Widget>[
        FlatButton(
            onPressed: () {
              _scrollController.animateTo(0,
                  duration: Duration(seconds: 1), curve: Curves.bounceInOut);
            },
            child: Text('position: ${position.floor()}')),
        Container(
          width: 0.3,
          height: 30,
        ),
        FlatButton(onPressed: () {}, child: Text(notify)),
        Visibility(
          visible: isEnd,
          child: FlatButton(onPressed: () {}, child: Text('到底了')),
        )
      ],
    );
  }
}
